let timerID = null;

self.addEventListener('message', function(event) {
  const seconds = event.data.seconds;

  // 清除之前的计时器
  if (timerID) {
    clearInterval(timerID);
    timerID = null;
  }

  let count = seconds;

  timerID = setInterval(function() {
    count--;
    if (count === 0) {
      clearInterval(timerID);
      self.postMessage({ timeout: true });
    } else {
      var times = setMinutes(count);
      var ddCountDown = times.day;
      var hhCountDown = times.hr;
      var mmCountDown = times.min;
      var ssCountDown = times.sec;
      self.postMessage({ count,ddCountDown,hhCountDown,mmCountDown,ssCountDown });
    }
    
    
  }, 1000);
});

function setMinutes(date) {
  var day = Math.floor(date / 60 / 60 / 24).toString().padStart(2, "0");
  var hr = Math.floor((date / 60 / 60) % 24).toString().padStart(2, "0");
  var min = Math.floor((date / 60) % 60).toString().padStart(2, "0");
  var sec = Math.floor(date % 60).toString().padStart(2, "0");
  return {
      day:day,
      hr:hr,
      min:min,
      sec:sec
  }
};

// ---------------------------------------------
// let countdownInterval;
// self.onmessage = function(event){
//     if(event.data === 'start'){
//         countdownInterval=setInterval(()=>{
//             self.postMessage('tick')
//         },1000);
//     }else if(event.data === 'stop'){
//         clearInterval(countdownInterval);
//         countdownInterval=setInterval(()=>{
//             self.postMessage('tick')
//         },1000);
//     }
// }

